<?php

namespace app\admin\controller;

use OSS\OssClient;
use app\model\File;
use think\facade\Request;
use think\facade\Filesystem;
use think\file\UploadedFile;
use app\common\entity\ResponseData;
use think\exception\ValidateException;
use OSS\Credentials\StaticCredentialsProvider;
use OSS\Credentials\EnvironmentVariableCredentialsProvider;

class Upload extends AdminBase
{
    public function upload()
    {
        try {
            // 获取上传文件
            $file = Request::file('file');
            if (!$file) {
                return json(['code' => 400, 'msg' => '请选择上传文件']);
            }
            // 验证规则
            $validate = [
                'file' => [
                    'fileSize' => 1024 * 1024 * 10, // 10MB
                    'fileExt'  => 'jpg,png,gif,jpeg,zip,rar',
                    'fileMime' => [
                        'image/jpeg',
                        'image/png',
                        'image/gif',
                        'application/zip',
                        'application/x-rar-compressed'
                    ]
                ]
            ];

            // 验证文件
            validate($validate)->check(['file' => $file]);

            // 保存文件
            $savename = Filesystem::disk('public')->putFile('uploads', $file);
            if ($savename) {
                $data = [
                    'path' => '/storage/' . $savename,
                    'name' => $file->getOriginalName()
                ];
                return json(['code' => 200, 'msg' => '上传成功', 'data' => $data]);
            }
            return json(['code' => 500, 'msg' => '文件保存失败']);
        } catch (ValidateException $e) {
            return json(['code' => 400, 'msg' => $e->getMessage()]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 阿里云上传
     * @param string $object
     * @param string $hash
     * @param string $type
     * @return \think\response\Json
     */
    public function oss($object, $hash, $type=''){
        $provider = new StaticCredentialsProvider(env('ali.accessKey'),env('ali.secretKey'));
        $config = array(  
            "provider" => $provider,
            "endpoint" => 'https://oss-cn-guangzhou.aliyuncs.com',
            'signatureVersion'=>OssClient::OSS_SIGNATURE_VERSION_V4,
            "region"=> "cn-guangzhou"
        );
        $ossClient = new OssClient($config);
        $file = File::where(['hash'=>$hash])->find();
        if($file){
            return ResponseData::success('', $file);
        }
        $filePath = explode('/', $object);
        $fileFormat = explode('.',$filePath[count($filePath) - 1]);
        $path = 'upload/'.date('Ymd').'/'.$hash.'.'.$fileFormat[count($fileFormat) - 1];
        $file = File::create([
            'name' => $filePath[count($filePath) - 1], 'hash' => $hash, 
            'url'=>env('ali.img_domain').'/'.$path, 'path' => $path,
            'status' => 0
        ]);
        // 生成预签名URL。
        $signedUrl = $ossClient->signUrl('vovoqi', 
            $path, 
            600, "PUT", ['Content-Type' => $type]
        );
        return ResponseData::success($signedUrl, $file);
    }

    // 本地上传
    public function local(){
        $file = request()->file('file');
        if (!$file) {
            return ResponseData::error('请选择上传文件');
        }
        $fileHash = md5_file($file);
        $f = File::where(['hash'=>$fileHash])->find();
        if ($f) {
            return ResponseData::success($f);
        }
        $path = public_path('uploads/'.date('Ym'));
        $filename = $fileHash.'.'.$file->getOriginalExtension();
        $localFile = $file->move($path, $filename);
        $file = File::create([
            'name' => $file->getOriginalName(),
            'hash' => $fileHash,
            'path' => $localFile,
            'url' => $this->request->domain().'/uploads/'.date('Ym').'/'.$filename,
            'user_id' => $this->request->user['id'],
            'status' => 1
        ]);
        return ResponseData::success($file);
    }
}
